const caseLabel = { fontFamily: 'var(--font-mono)', fontWeight: 500, fontSize: 9.5, letterSpacing: 'var(--tracking-label)', textTransform: 'uppercase', color: 'var(--gray-500)' };

function CaseRow({ item, t, href, onOpen, last, badge, dark }) {
  const [h, setH] = React.useState(false);
  const { Icon } = window.SevcikMarketingDesignSystem_3203fa;
  const label = { ...caseLabel, color: dark ? 'var(--gray-on-dark-500)' : 'var(--gray-500)' };
  return (
    <a href={href || undefined} onMouseEnter={() => setH(!!href)} onMouseLeave={() => setH(false)} onClick={(e) => { e.preventDefault(); if (onOpen) onOpen(); }}
      className="sm-case-row" aria-disabled={!href}
      style={{
        display: 'grid', gridTemplateColumns: '116px 132px minmax(0, 1.4fr) minmax(160px, 1fr) auto', alignItems: 'center', gap: 22,
        padding: '26px 28px', textDecoration: 'none', cursor: href ? 'pointer' : 'default',
        borderBottom: last ? 'none' : `1.5px solid ${dark ? 'var(--border-hairline-dark)' : 'var(--gray-200)'}`,
        backgroundColor: h ? (dark ? 'rgba(255,255,255,0.06)' : 'var(--gray-150)') : 'transparent', transition: 'background-color .25s ease',
      }}>
      <div style={{ ...label, display: 'flex', flexDirection: 'column', gap: 6 }}>
        <span>{item.year}</span>
        {badge && <span style={{ alignSelf: 'flex-start', padding: '3px 8px', borderRadius: 999, background: dark ? 'var(--white)' : 'var(--black)', color: dark ? 'var(--black)' : 'var(--white)' }}>{badge}</span>}
      </div>
      <div style={{ height: badge ? 88 : 0, borderRadius: 10, overflow: 'hidden' }}>
        {badge && <GradientArt gradient={item.art} radius={10} hover={h} />}
      </div>
      <div style={{ minWidth: 0, transform: h ? 'translateX(4px)' : 'none', transition: 'transform .3s cubic-bezier(.22,1,.36,1)' }}>
        <h3 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 22, lineHeight: 1.22, letterSpacing: '-0.015em', color: dark ? 'var(--white)' : 'var(--black)' }}>{item.title}</h3>
        <div style={{ marginTop: 6, fontFamily: 'var(--font-meta)', fontWeight: 500, fontSize: 12.5, color: dark ? 'var(--gray-on-dark-400)' : 'var(--gray-600)' }}>{item.category}</div>
      </div>
      <div className="sm-case-metrics" style={{ display: 'flex', alignItems: 'center' }}>
        <span style={{ ...label, padding: '5px 10px', borderRadius: 999, border: `1.5px solid ${dark ? 'rgba(255,255,255,0.22)' : 'var(--gray-300)'}`, color: dark ? 'var(--gray-on-dark-400)' : 'var(--gray-600)', whiteSpace: 'nowrap' }}>{t.soonBadge}</span>
      </div>
      <span style={{ width: 34, height: 34, flexShrink: 0, borderRadius: 'var(--radius-card)', display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: h ? (dark ? 'var(--white)' : 'var(--black)') : (dark ? 'rgba(255,255,255,0.08)' : 'rgba(10,10,10,0.05)'), transition: 'background-color .25s ease' }}>
        <Icon name="arrow-up-right" size={15} color={h ? (dark ? 'var(--black)' : 'var(--white)') : (dark ? 'var(--white)' : 'var(--black)')} />
      </span>
    </a>
  );
}

/* While the write-ups are being cleared with clients, rows are inert and the
   list carries one honest note. CaseStudyReader below stays as the agreed
   design for when the first study is ready. */
function CaseStudies({ s, t, onBack, onOpenCase }) {
  const theme = useReaderTheme();
  const { dark, C } = theme;
  const hrefOf = (c) => routeHref({ lang: s.htmlLang, screen: 'cases', slug: c.slug });
  return (
    <ScreenOverlay onClose={onBack} backLabel={t.backHome} meta={s.cases.length ? `${s.cases.length} ${t.caseStudiesCount}` : t.emptyCases} zIndex={60} maxWidth={980} theme={theme} t={t}>
      <OverlayTitle title={t.caseStudies} blurb={s.casesBlurb} C={C} />
      <div style={{ background: C.card, borderRadius: 'var(--radius-card)', overflow: 'hidden', transition: 'background-color .35s ease' }}>
        {s.cases.length === 0 && <EmptyState title={t.emptyCases} note={t.emptyCasesNote} gradient="var(--gradient-thumb-warm)" C={C} />}
        {s.cases.map((c, i) => (
          <CaseRow key={c.id} item={c} t={t} href={c.soon ? null : hrefOf(c)} onOpen={c.soon ? null : () => onOpenCase(c)} last={i === s.cases.length - 1} badge={!c.soon && i === 0 ? t.latestBadge : null} dark={dark} />
        ))}
      </div>
      {s.cases.some((c) => c.soon) && (
        <p style={{ margin: '22px 0 0', maxWidth: '58ch', fontFamily: 'var(--font-body)', fontSize: 15.5, lineHeight: 1.65, color: C.stand, textWrap: 'pretty' }}>{t.soonNote}</p>
      )}
    </ScreenOverlay>
  );
}

function Bar({ caption, pct, strong, C = READER_C.light }) {
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12, marginBottom: 8 }}>
        <span style={{ ...caseLabel, color: C.meta }}>{caption}</span>
        <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 17, letterSpacing: '-0.01em', color: strong ? C.heading : C.meta }}>-</span>
      </div>
      <div style={{ height: 10, borderRadius: 999, background: C.rule, overflow: 'hidden' }}>
        <div style={{ height: '100%', width: `${pct}%`, borderRadius: 999, backgroundColor: strong ? C.heading : C.meta }}></div>
      </div>
    </div>
  );
}

function CaseStudyReader({ s, t, item, onBack, onOpenCase }) {
  const { Icon } = window.SevcikMarketingDesignSystem_3203fa;
  const c = item || s.cases[0];
  const [shown, setShown] = React.useState(false);
  const [progress, setProgress] = React.useState(0);
  const [backHover, setBackHover] = React.useState(false);
  const theme = useReaderTheme();
  const { dark, C } = theme;
  const label = { ...caseLabel, color: C.meta };
  const scroller = React.useRef(null);
  const idx = s.cases.findIndex((x) => x.id === c.id);
  const next = s.cases[(idx + 1) % s.cases.length];

  React.useEffect(() => {
    const id = requestAnimationFrame(() => setShown(true));
    const to = setTimeout(() => setShown(true), 60);
    const onKey = (e) => { if (e.key === 'Escape') onBack(); };
    window.addEventListener('keydown', onKey);
    const prev = document.documentElement.style.overflow;
    document.documentElement.style.overflow = 'hidden';
    return () => { cancelAnimationFrame(id); clearTimeout(to); window.removeEventListener('keydown', onKey); document.documentElement.style.overflow = prev; };
  }, [onBack]);
  React.useEffect(() => { if (scroller.current) scroller.current.scrollTop = 0; setProgress(0); }, [c.id]);

  const onScroll = (e) => {
    const el = e.currentTarget;
    const max = el.scrollHeight - el.clientHeight;
    setProgress(max > 0 ? Math.min(1, el.scrollTop / max) : 0);
  };

  const body = { margin: 0, fontFamily: 'var(--font-body)', fontSize: 19, lineHeight: 1.75, color: C.body };
  const h2 = { margin: 0, fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 30, lineHeight: 1.2, letterSpacing: '-0.015em', color: C.heading };
  const facts = [[t.facts[0], c.title], [t.facts[1], '[TODO: sector]'], [t.facts[2], c.category], [t.facts[3], '[TODO: duration]']];
  const chapters = s.htmlLang === 'cs'
    ? [
        { n: '01', h: 'Zadání', p: '[TODO: případová studie - v jaké situaci klient byl a proč na tom záleželo, ~110 slov]' },
        { n: '02', h: 'Postup', p: '[TODO: případová studie - co se konkrétně dělalo, v pořadí, ~130 slov]' },
        { n: '03', h: 'Výsledek', p: '[TODO: případová studie - co se změnilo, s čísly v kontextu, ~90 slov]' },
      ]
    : [
        { n: '01', h: 'The challenge', p: '[TODO: case study - the situation the client was in and why it mattered, ~110 words]' },
        { n: '02', h: 'The approach', p: '[TODO: case study - what was actually done, in order, ~130 words]' },
        { n: '03', h: 'The outcome', p: '[TODO: case study - what changed, with the numbers restated in context, ~90 words]' },
      ];

  return (
    <div ref={scroller} onScroll={onScroll} className="sm-reader-layer"
      style={{
        position: 'fixed', inset: 0, zIndex: 80, background: C.bg, overflowY: 'auto',
        opacity: shown ? 1 : 0, transform: shown ? 'translateX(0)' : 'translateX(56px)',
        transition: 'opacity .4s ease, transform .5s cubic-bezier(.22,1,.36,1), background-color .35s ease',
      }}>
      <div style={{ position: 'fixed', top: 0, left: 0, right: 0, height: 3, zIndex: 2 }}>
        <div style={{ height: '100%', width: `${progress * 100}%`, background: C.progress, transition: 'width .1s linear' }}></div>
      </div>
      <div style={{ position: 'relative', zIndex: 1, background: C.bg, borderBottom: `1.5px solid ${C.rule}`, transition: 'background-color .35s ease' }}>
        <div style={{ maxWidth: 1080, margin: '0 auto', padding: '14px 24px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 20 }}>
          <button onClick={onBack} onMouseEnter={() => setBackHover(true)} onMouseLeave={() => setBackHover(false)}
            style={{ display: 'flex', alignItems: 'center', gap: 10, minHeight: 44, border: 'none', background: 'transparent', cursor: 'pointer', padding: 0, fontFamily: 'var(--font-mono)', fontWeight: 500, fontSize: 9.5, letterSpacing: 'var(--tracking-label)', textTransform: 'uppercase', color: backHover ? C.heading : C.stand, transition: 'color .25s ease' }}>
            <span style={{ width: 32, height: 32, borderRadius: 'var(--radius-card)', display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: backHover ? C.chipHover : C.chip, transition: 'background-color .25s ease' }}>
              <Icon name="arrow-up-left" size={15} color={backHover ? C.chipInkHover : C.chipInk} />
            </span>
            {t.backCases}
          </button>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <span style={label}>{c.year} · {c.category}</span>
            <ThemeChip theme={theme} t={t} />
          </div>
        </div>
      </div>

      <header style={{ maxWidth: 1080, margin: '0 auto', padding: '72px 24px 0' }}>
        <div style={label}>{t.caseStudyLabel}</div>
        <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 'clamp(40px, 5.4vw, 72px)', lineHeight: 1.02, letterSpacing: '-0.025em', color: C.heading, margin: '18px 0 0' }}>{c.title}</h1>
        <p style={{ fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 23, lineHeight: 1.5, color: C.stand, margin: '20px 0 0', maxWidth: '46ch' }}>[TODO: case study - standfirst, one sentence on the result]</p>
        <GradientArt gradient={c.art} minHeight={380} style={{ margin: '44px 0 0' }} />
      </header>

      <section className="sm-case-facts" style={{ maxWidth: 1080, margin: '0 auto', padding: '10px 24px 0', display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10 }}>
        {facts.map(([k, v]) => (
          <div key={k} style={{ background: C.card, borderRadius: 'var(--radius-card)', padding: '20px 22px', marginTop: 10, transition: 'background-color .35s ease' }}>
            <div style={label}>{k}</div>
            <div style={{ fontFamily: 'var(--font-meta)', fontWeight: 500, fontSize: 15.5, lineHeight: 1.3, color: C.heading, marginTop: 10 }}>{v}</div>
          </div>
        ))}
      </section>

      <section className="sm-case-split" style={{ maxWidth: 1080, margin: '0 auto', padding: '10px 24px 0', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        <div style={{ background: C.card, borderRadius: 'var(--radius-card)', padding: '32px 30px', transition: 'background-color .35s ease' }}>
          <div style={label}>{t.keyResults}</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 22, marginTop: 22 }}>
            {[0, 1, 2].map((i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'baseline', gap: 16, paddingBottom: 22, borderBottom: i === 2 ? 'none' : `1.5px solid ${C.rule}` }}>
                <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 40, lineHeight: 1, letterSpacing: '-0.03em', color: C.heading, minWidth: 90 }}>-</span>
                <span style={{ fontFamily: 'var(--font-body)', fontSize: 15, lineHeight: 1.5, color: C.stand }}>[TODO: result - what the number measures, ~10 words]</span>
              </div>
            ))}
          </div>
        </div>
        <div style={{ background: C.card, borderRadius: 'var(--radius-card)', padding: '32px 30px', transition: 'background-color .35s ease' }}>
          <div style={label}>{t.beforeAfter}</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 22, marginTop: 26 }}>
            <Bar caption="[TODO: metric]" pct={28} C={C} />
            <Bar caption="[TODO: metric]" pct={82} strong C={C} />
            <Bar caption="[TODO: metric]" pct={44} C={C} />
            <Bar caption="[TODO: metric]" pct={71} strong C={C} />
          </div>
          <p style={{ ...label, marginTop: 26 }}>{t.barsNote}</p>
        </div>
      </section>

      <section style={{ maxWidth: 720, margin: '0 auto', padding: '72px 24px 0', display: 'flex', flexDirection: 'column', gap: 56 }}>
        {chapters.map((ch) => (
          <div key={ch.n}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 16 }}>
              <span className="sm-mono" style={{ fontFamily: 'var(--font-mono)', fontWeight: 500, fontSize: 9.5, color: C.meta }}>{ch.n}</span>
              <h2 style={h2}>{ch.h}</h2>
            </div>
            <p style={{ ...body, marginTop: 20 }}>{ch.p}</p>
          </div>
        ))}
        {c.quote && (
          <blockquote style={{ margin: 0, background: C.card, borderRadius: 'var(--radius-card)', padding: '34px 32px', transition: 'background-color .35s ease' }}>
            <p style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 22, lineHeight: 1.45, color: C.heading }}>{c.quote}</p>
            {c.quoteBy && <footer style={{ ...label, marginTop: 20 }}>{c.quoteBy}</footer>}
          </blockquote>
        )}
      </section>

      <div style={{ maxWidth: 1080, margin: '0 auto', padding: '72px 24px 96px' }}>
        <div style={{ borderTop: `1.5px solid ${C.rule}`, paddingTop: 28 }}>
          <div style={{ ...label, marginBottom: 14 }}>{t.nextCase}</div>
          <div style={{ background: C.card, borderRadius: 'var(--radius-card)', overflow: 'hidden', transition: 'background-color .35s ease' }}>
            <CaseRow item={next} t={t} href={routeHref({ lang: s.htmlLang, screen: 'cases', slug: next.slug })} onOpen={() => onOpenCase(next)} last dark={dark} />
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CaseStudies, CaseStudyReader });
